import { message } from 'ant-design-vue'
// import { Base64 } from 'js-base64'
import axios, { type AxiosRequestConfig } from 'axios'
import api from '../api'
// import router from '@/router'
type MyConfig = AxiosRequestConfig & { hideMsg?: boolean }
const request = async <T = any>(config: MyConfig): Promise<T> => {
  config.headers = config.headers || {}
  if (import.meta.env.DEV) {
    config.headers.account = import.meta.env.VITE_APP_USER
  }
  // const userStore = useUserStore();
  // if (userStore.userInfo) {
  //   const obj = {
  //     orgId: userStore.userInfo.orgId,
  //     unitOrgId: userStore.userInfo.unitOrgInfo.id,
  //     queryId: undefined,
  //   };
  //   //添加查询器
  //   const queryId = getQueryIdByRoute();
  //   if (queryId) {
  //     obj.queryId = queryId;
  //   } else {
  //     delete obj.queryId;
  //   }
  //   //取路由跳转取值的查询器编码
  //   const userInfo = JSON.stringify(obj);
  //   config.headers['Access-Info'] = Base64.encode(userInfo);
  // }
  config.headers['Token'] = localStorage.getItem('token')

  try {
    const res = await axios(config)
    if (config.responseType == 'blob') {
      // @ts-ignore
      return Promise.resolve(res)
    }
    if (res.data.success == true) {
      return Promise.resolve(res.data.data)
    } else {
      throw res.data
    }
  } catch (error: any) {
    // 未登录

    if (error?.response?.data?.code == '1001') {
      window.location.href = error.response.data.data
    }
    if (!config.hideMsg) {
      const msg = error.errorMessage || error.error
      if (msg) {
        message.error(msg)
      }
    }
    return Promise.reject(error)
  }
}
const post = <T = any>(url: string, data: AxiosRequestConfig['data'] = {}, config: MyConfig = {}) =>
  request<T>({ url, method: 'post', data, ...config })
const put = <T = any>(url: string, data: AxiosRequestConfig['data'] = {}, config: MyConfig = {}) =>
  request<T>({ url, method: 'put', data, ...config })
const get = <T = any>(
  url: string,
  params: AxiosRequestConfig['params'] = {},
  config: MyConfig = {}
) => request<T>({ url, method: 'get', params, ...config })
const del = <T = any>(
  url: string,
  params: AxiosRequestConfig['params'] = {},
  config: MyConfig = {}
) => request<T>({ url, method: 'delete', params, ...config })
const log = (
  params: { entityId: string; operation: string; newValue: any; oldValue: any; fieldName: string }[]
) => post(api.acmMdm.operationAuditLog.saveBatch, { auditLogs: params })
const exportFile = async <T = any>(
  url: string,
  data: AxiosRequestConfig['data'] = {},
  config: MyConfig = {}
) => {
  const res: any = await request<T>({
    url,
    method: 'post',
    data,
    ...config,
    responseType: 'blob'
  })
  const headers = res.headers

  const contentDisposition = headers['content-disposition'] || ''
  let reqFileName = contentDisposition.substring(
    contentDisposition.indexOf("utf-8''"),
    contentDisposition.length
  )
  reqFileName = reqFileName.replace("utf-8''", '').replace(/"/g, '')
  reqFileName = decodeURIComponent(reqFileName)
  const content = res.data as Blob

  // @ts-ignore
  if (content == null || content == 'application/json') {
    message.error('下载失败')
    return
  }

  const blob = new Blob([content], { type: content.type })
  if ('download' in document.createElement('a')) {
    const elink = document.createElement('a')
    elink.download = reqFileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    setTimeout(function () {
      URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }, 3000)
    return content
  } else {
    // @ts-ignore
    window.navigator.msSaveBlob(blob, file.attName)
    return content
  }
}
const req = {
  post,
  get,
  delete: del,
  put,
  exportFile,
  log
}

// const getQueryIdByRoute = () => {
//   const path = router.currentRoute.value.path
//   let queryId = null
//   const fullPath = '/engineering/#' + path
//   const { userInfo } = useUserStore()
//   const list = userInfo.queryResources
//   for (let i = 0; i < list?.length; i++) {
//     const item = list[i] || {}
//     if (item.url == fullPath) {
//       queryId = item.id
//     }
//   }
//   return queryId
// }

export default req
